"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 二级分区
Case Name   : list_hash二级分区表:逻辑复制
Create At   : 2022/2/17
Owner       : @daiguatutu
Description :
    1.修改参数wal_level为logical;enable_slot_log为on
    2.主机配置逻辑复制的用户
    3.主机创建并查询逻辑复制槽
    4.主机执行增删改sql业务
    5.启动逻辑复制槽
    6.清理环境
Expect      :
    1.修改成功
    2.配置成功
    3.成功
    4.成功
    5.成功,sql操作记录到复制槽中
    6.清理成功
History     :
"""
import os
import unittest
from time import sleep
from yat.test import Node
from yat.test import macro

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class Subpartition(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.primaryNode = Node('PrimaryDbUser')
        self.constant = Constant()
        self.common = Common()
        self.t_name = 't_subpartition_0179'
        self.ts_name = 'ts_subpartition_0179'
        self.slot_name = "slot_subpartition_0179"
        self.default_value1 = self.common.show_param('wal_level')
        self.default_value2 = self.common.show_param('enable_slot_log')

    def test_subpartition(self):
        text = '-----step1:修改以下参数值;expect: 修改成功-----'
        self.log.info(text)
        param_value = ['wal_level=logical', 'enable_slot_log=on']
        for value in param_value:
            msg = self.pri_sh.execute_gsguc('set',
                                            self.constant.GSGUC_SUCCESS_MSG,
                                            f'{value}')
            self.assertTrue(msg, '执行失败:' + text)
        restart_msg = self.pri_sh.restart_db_cluster()
        self.assertTrue(restart_msg, '执行失败' + text)

        text = '-----step2:主机配置逻辑复制的用户;expect:配置成功-----'
        self.log.info(text)
        guc_cmd = f'source {macro.DB_ENV_PATH}; ' \
            f'gs_guc reload -D {macro.DB_INSTANCE_PATH} ' \
            f'-h "local  replication  {self.primaryNode.ssh_user} trust " '
        self.log.info(guc_cmd)
        guc_res = self.primaryNode.sh(guc_cmd).result()
        self.log.info(guc_res)
        self.assertIn(self.constant.GSGUC_SUCCESS_MSG, guc_res,
                      '执行失败:' + text)

        text = '-----step3:主机创建并查询逻辑复制槽;expect:成功-----'
        self.log.info(text)
        create_sql = f"select * from pg_drop_replication_slot" \
            f"('{self.slot_name}');" \
            f"select * from pg_create_logical_replication_slot" \
            f"('{self.slot_name}','mppdb_decoding');" \
            f"select * from pg_get_replication_slots() " \
            f"where slot_name='{self.slot_name}';"
        msg = self.pri_sh.execut_db_sql(create_sql)
        self.log.info(msg)
        self.assertIn('slot_subpartition_0179', msg.splitlines()[-2],
                      '执行失败:' + text)

        text = '-----step4:主机执行sql业务 expect:成功-----'
        self.log.info(text)
        create_sql = f"drop table if exists {self.t_name};" \
            f"drop tablespace if exists {self.ts_name};" \
            f"create tablespace {self.ts_name} relative location " \
            f"'{self.ts_name}';" \
            f"create table if not exists {self.t_name}(" \
            f"col_1 int ,col_2 int ,col_3 varchar2 ( 30 ) " \
            f"not null ,col_4 int)tablespace {self.ts_name} " \
            f"partition by list (col_1) subpartition by hash (col_2) " \
            f"( partition p_list_1 values (-1,-2,-3,-4,-5,-6,-7,-8,-9,-10) " \
            f"  ( subpartition p_hash_1_1 , subpartition p_hash_1_2 ," \
            f"    subpartition p_hash_1_3 ), " \
            f"  partition p_list_2 values (1,2,3,4,5,6,7,8,9,10) " \
            f"  ( subpartition p_hash_2_1 , subpartition p_hash_2_2 , " \
            f"    subpartition p_hash_2_3 , subpartition p_hash_2_4 , " \
            f"    subpartition p_hash_2_5 ), " \
            f"  partition p_list_3 values (11,12,13,14,15,16,17,18,19,20), " \
            f"  partition p_list_4 values (21,22,23,24,25,26,27,28,29,30 ) " \
            f"  ( subpartition p_hash_4_1 ), " \
            f"  partition p_list_5 values (default) " \
            f"  ( subpartition p_hash_5_1 ), " \
            f"  partition p_list_6 values (31,32,33,34,35,36,37,38,39,40) " \
            f"  ( subpartition p_hash_6_1 , subpartition p_hash_6_2 , " \
            f"    subpartition p_hash_6_3 )) enable row movement ; " \
            f"insert into {self.t_name} values (generate_series(0, 19)," \
            f"generate_series(0, 1000),generate_series(0, 99));" \
            f"update {self.t_name} set col_2=8 where col_2=4;" \
            f"delete {self.t_name} where col_2=8;" \
            f"insert into  {self.t_name} values (1,1,1,1);"
        msg = self.pri_sh.execut_db_sql(create_sql)
        self.log.info(msg)
        self.assertIn(self.constant.TABLESPCE_CREATE_SUCCESS, msg,
                      '执行失败:' + text)
        self.assertIn(self.constant.TABLESPCE_DROP_SUCCESS, msg,
                      '执行失败:' + text)
        self.assertIn(self.constant.CREATE_TABLE_SUCCESS, msg, '执行失败:' + text)
        self.assertIn(self.constant.DROP_TABLE_SUCCESS, msg, '执行失败:' + text)
        self.assertIn(self.constant.INSERT_SUCCESS_MSG, msg, '执行失败:' + text)
        self.assertIn(self.constant.UPDATE_SUCCESS_MSG, msg, '执行失败:' + text)
        self.assertIn(self.constant.DELETE_SUCCESS_MSG, msg, '执行失败:' + text)

        text = '-----step5:启动逻辑复制槽; expect:成功,sql操作记录到复制槽中-----'
        self.log.info(text)
        start_cmd = f"pg_recvlogical " \
            f"-d {self.primaryNode.db_name} " \
            f"-S {self.slot_name} " \
            f"-p {str(int(self.primaryNode.db_port) + 1)} " \
            f"-s 2 " \
            f"-f - " \
            f"--start "
        execute_cmd = f'''source {macro.DB_ENV_PATH}
                           expect <<EOF
                           set timeout 30
                           spawn {start_cmd}
                           expect "Password:"
                           send "{macro.COMMON_PASSWD}\\n"
                           expect eof\n''' + '''EOF'''
        self.log.info(execute_cmd)
        exec_msg = self.primaryNode.sh(execute_cmd).result()
        self.log.info(exec_msg)
        self.assertEqual(6, exec_msg.count(self.constant.COMMIT_SUCCESS_MSG),
                         '执行失败:' + text)

    def tearDown(self):
        self.log.info('-----step6:清理环境-----')
        self.log.info('--杀掉pg_recvlogical进程--')
        kill_cmd = "ps aux|grep 'pg_recvlogical'|grep -v " \
                   "grep|tr -s ' '|cut -d ' ' -f 2|xargs kill -9"
        self.log.info(kill_cmd)
        kill_msg = self.primaryNode.sh(kill_cmd).result()
        self.log.info(kill_msg)
        sleep(5)

        text_1 = '-----删除表，表空间,复制槽 expect:成功-----'
        self.log.info(text_1)
        del_cmd = f"drop table if exists {self.t_name};" \
            f"drop tablespace if exists {self.ts_name};" \
            f"select * from pg_drop_replication_slot('{self.slot_name}');"
        drop_cmd = self.pri_sh.execut_db_sql(del_cmd)
        self.log.info(drop_cmd)
        sql_cmd = self.pri_sh.execut_db_sql(f"select * from "
                                            f"pg_replication_slots;")
        self.log.info(sql_cmd)

        text_2 = '-----主机pg_hba.conf文件恢复 expect:成功-----'
        self.log.info(text_2)
        guc_cmd = f'source {macro.DB_ENV_PATH}; ' \
            f'gs_guc reload -D {macro.DB_INSTANCE_PATH} ' \
            f'-h "local  replication  {self.primaryNode.ssh_user} " '
        self.log.info(guc_cmd)
        guc_res = self.primaryNode.sh(guc_cmd).result()
        self.log.info(guc_res)

        text_3 = '-----恢复参数默认值并重启数据库 expect:成功-----'
        self.log.info(text_3)
        res_cmd1 = self.pri_sh.execute_gsguc('set',
                                             self.constant.GSGUC_SUCCESS_MSG,
                                             f'wal_level='
                                             f'{self.default_value1}')
        self.log.info(res_cmd1)
        res_cmd2 = self.pri_sh.execute_gsguc('set',
                                             self.constant.GSGUC_SUCCESS_MSG,
                                             f'enable_slot_log='
                                             f'{self.default_value2}')
        self.log.info(res_cmd2)
        restart_msg = self.pri_sh.restart_db_cluster()

        self.log.info('-----断言tearDown执行成功-----')
        self.assertIn(self.constant.TABLE_DROP_SUCCESS, drop_cmd,
                      '执行失败:' + text_1)
        self.assertIn(self.constant.TABLESPCE_DROP_SUCCESS, drop_cmd,
                      '执行失败:' + text_1)
        self.assertNotIn(self.slot_name, sql_cmd, '执行失败:' + text_1)
        self.assertIn(self.constant.GSGUC_SUCCESS_MSG, guc_res,
                      '执行失败:' + text_2)
        self.assertTrue(res_cmd1, '执行失败:' + text_3)
        self.assertTrue(res_cmd2, '执行失败:' + text_3)
        self.assertTrue(restart_msg, '执行失败:' + text_3)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
